<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="form.id ? '修改' : '新增'"
    width="800"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="85"
      size="default"
      label-position="top"
    >
      <el-row :gutter="21">
        <el-col :span="12">
          <el-form-item label="目标类型" prop="tag_type">
            <VGroup>
              <el-select
                class="!w-[180px]"
                v-model="form.target_rule"
                placeholder="目标对象"
                @change="changeRole"
                :disabled="handleType == 'edit'"
              >
                <el-option
                  v-for="item in constharacterOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select
                class="!w-[180px]"
                v-model="form.target_type"
                placeholder="目标类型"
                @change="changeType"
                :disabled="handleType == 'edit'"
              >
                <el-option
                  v-for="item in designOptionsFilter"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </VGroup>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标维度" prop="tag_type">
            <el-select
              v-model="form.dimensionality"
              placeholder="请选择"
              class="w-full"
              @change="changeDimension"
              :disabled="handleType == 'edit'"
            >
              <el-option
                v-for="item in dimensionOptionsFilter"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标周期" prop="tag_type">
            <el-date-picker
              v-model="form.target_month"
              type="month"
              value-format="YYYY-MM-DD"
              placeholder="请选择月份"
              :disabled="handleType == 'edit'"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              placeholder="请输入备注"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <el-button class="mb-2" type="primary">批量新增</el-button> -->
    <div class="flex justify-end pb-2">
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>
    <el-table
      :data="paginatedData"
      height="400"
      style="width: 100%"
      border
      ref="multipleTableRef"
      :row-class-name="rowClassName"
    >
      <el-table-column
        prop="tag_name"
        label="目标部门"
        v-if="form.dimensionality_type == 2"
      >
        <template #default="{ row }">
          <SelectDepartment
            v-model="row.user_or_depart"
            placeholder="请选择"
          ></SelectDepartment>
        </template>
      </el-table-column>
      <el-table-column
        prop="user_or_depart"
        label="目标人员"
        v-if="form.dimensionality_type == 1"
      >
        <template #default="{ row }">
          <SelectPersonnel
            class="w-full"
            v-model="row.user_or_depart"
            placeholder="请选择"
            @change="changeUser($event, row)"
          ></SelectPersonnel>
        </template>
      </el-table-column>
      <el-table-column
        prop="last_category"
        label="目标分类"
        v-if="form.dimensionality_type == 3"
      >
        <template #default="{ row }">
          <SelectCategory
            class="w-full"
            v-model="row.last_category"
            :defaultProps="defaultProps"
            :showAllLevels="true"
          ></SelectCategory>
        </template>
      </el-table-column>
      <el-table-column
        prop="last_category"
        label="平台/站点"
        v-if="form.dimensionality_type == 3"
      >
        <template #default="{ row }">
          <SelectPlatformSite
            v-model:platform="row.platform_id"
            v-model:site="row.site_id"
            valueSizeKey="site_id"
            @changePlatform="changePlatform($event, row)"
            @changeSiteInfo="changeSite($event, row)"
          ></SelectPlatformSite>
        </template>
      </el-table-column>

      <el-table-column prop="target_value" label="目标值">
        <template #header="{ row }">
          <div>
            目标值
            <el-button type="primary" link @click="hanldeBatch('value')">批量</el-button>
          </div>
        </template>
        <template #default="{ row }">
          <el-input
            class="w-full"
            v-model="row.target_value"
            placeholder="请输入目标值"
            type="text"
            oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
          />
        </template>
      </el-table-column>
      <el-table-column prop="target_manage" label="目标负责人">
        <template #header="{ row }">
          <div>
            目标负责人
            <el-button type="primary" link @click="hanldeBatch('manage')">批量</el-button>
          </div>
        </template>
        <template #default="{ row }">
          <select-personnel
            class="w-full"
            v-model="row.target_manage"
            placeholder="请选择"
          ></select-personnel>
        </template>
      </el-table-column>
      <el-table-column prop="tag_count" label="操作" width="60">
        <template #default="{ row, $index }">
          <el-button type="danger" link @click="handleDelete(row, $index)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-end py-2">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="form.goods_target_config_detail.length"
        layout="prev, pager, next, jumper, total"
        @current-change="handleCurrentChange"
      />
    </div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >保 存</el-button
      >
    </template>
  </el-dialog>
  <el-dialog v-model="visibleBatch" title="批量维护目标" width="400" @close="batchClose">
    <el-form
      :model="batchForm"
      label-align="right"
      label-width="85"
      size="default"
      label-position="top"
    >
      <el-form-item label="目标值" v-if="batch_type == 'value'">
        <el-input
          class="w-full"
          v-model="batchForm.target_value"
          placeholder="请输入目标值"
          type="text"
        />
      </el-form-item>
      <el-form-item label="目标负责人" v-if="batch_type == 'manage'">
        <select-personnel
          class="w-full"
          v-model="batchForm.target_manage"
          placeholder="请选择"
        ></select-personnel>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="batchClose">取 消</el-button>
      <el-button type="primary" @click="batchSave()">保 存</el-button>
    </template>
  </el-dialog>
  <createItem ref="createItemRef" @create="hanldeCreateConfirm"></createItem>
</template>
<script setup name="ComModal">
import { createGoodsTargetConfig, editGoodsTargetConfig } from "../api";
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { constharacterOptions, dimensionOptions, designOptions } from "../data.js";
import SelectDepartment from "@/components/SelectDepartment/index.vue";
import SelectCategory from "@/components/SelectCategory/index.vue";
import SelectPersonnel from "@/components/SelectPersonnel/index.vue";
import { deepClone, getNowMonthDay } from "@/utils/index.js";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import useCommonStore from "@/store/modules/common";
import createItem from "./createItem.vue";
const commonStore = useCommonStore();

const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: true,
};

const emits = defineEmits(["query"]);

const statusMap = new Map([
  ["add", "新增商品目标配置"],
  ["edit", "编辑商品目标配置"],
  ["cope", "新增商品目标配置"],
  ["view", "查看商品目标配置"],
]);

const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  rules: {},
  handleType: "",
  visibleBatch: false,
  batchForm: {},
  batch_type: "",
  title: "",
  load: false,
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页显示的数量
  visibleCreate: false,
  createForm: {},
});

const {
  rules,
  form,
  visible,
  loading,
  formRef,
  handleType,
  visibleBatch,
  batch_type,
  batchForm,
  title,
  load,
  currentPage,
  pageSize,
  visibleCreate,
} = toRefs(data);

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return form.value.goods_target_config_detail.slice(start, end);
});

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const open = async (type, row) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  if (type == "edit") {
    form.value = row;
    form.value.dimensionality_type = row.dimensionality;
  } else if (type == "copy") {
    form.value = deepClone(row);
    form.value.current_dimensionality = form.value.dimensionality;
    form.value.current_target_type = form.value.target_type;
    form.value.current_target_rule = form.value.target_rule;
    delete form.value.id;
    delete form.value.target_status;
    delete form.value.target_status_text;
  } else {
    form.value = getForm();
  }
  visible.value = true;
};

const save = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      const formData = Object.assign({}, form.value);
      const targetValues = [];
      const seenValues = new Set();

      let hasDuplicate = false;

      // 遍历生成目标值并检测重复
      for (const item of formData.goods_target_config_detail) {
        let targetValue;

        if (formData.dimensionality === 1 || formData.dimensionality === 2) {
          // 异常处理：确保 user_or_depart 存在
          if (!item.user_or_depart) {
            ElMessage.error("目标人员或部门字段缺失");
            return;
          }
          targetValue = !item.delete && item.user_or_depart;
        } else {
          // 异常处理：确保 last_category 存在
          if (!item.last_category) {
            ElMessage.error("最后一级分类字段缺失");
            return;
          }
          targetValue = !item.delete && item.last_category;
        }

        // 检查是否重复
        if (targetValue && seenValues.has(targetValue)) {
          hasDuplicate = true;
          break;
        }

        if (targetValue) {
          targetValues.push(targetValue);
          seenValues.add(targetValue);
        }
      }

      // 检测重复并提示错误
      if (hasDuplicate) {
        ElMessage.error("目标人员或者部门不能重复");
        return;
      }

      loading.value = true;
      if (formData.id) {
        editGoodsTargetConfig(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        createGoodsTargetConfig(formData)
          .then((res) => {
            ElMessage.success(res.message);
            emits("query");
            close();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

// 初始化
const getForm = () => {
  return {
    target_rule: "",
    target_type: "",
    dimensionality: "",
    target_month: getNowMonthDay(),
    remark: "",
    goods_target_config_detail: [],
  };
};

const close = () => {
  visible.value = false;
};

// promise 封装二次确认
const handleConfirm = async (title) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(title, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};
// 修改目标对象
const changeRole = async (val) => {
  if (!form.value.current_target_rule) {
    form.value.current_target_rule = val;
  } else {
    const is_flag = await handleConfirm("是否更换目标角色，点击确认将清空目标类型?");
    if (is_flag) {
      form.value.target_type = "";
      form.value.current_target_type = "";
    } else {
      form.value.target_rule = form.value.current_target_rule;
    }
  }
};

const changeType = async (val) => {
  if (form.value.goods_target_config_detail.length == 0) {
    return;
  }
  if (!form.value.current_target_type) {
    form.value.current_target_type = val;
  } else {
    const is_flag = await handleConfirm("是否更换目标角色，点击确认将清空目标详情?");
    if (is_flag) {
      form.value.goods_target_config_detail = [];
    } else {
      form.value.target_type = form.value.current_target_type;
    }
  }
};

// 修改目标维度
const changeDimension = async (val) => {
  if (!form.value.current_dimensionality) {
    form.value.current_dimensionality = val;
    form.value.dimensionality_type = val;
    form.value.goods_target_config_detail = [];
  } else {
    const is_flag = await handleConfirm(
      "是否更换目标维度，点击确认将清空目标详情、目标类型?"
    );
    if (is_flag) {
      form.value.target_type = "";
      form.value.current_target_type = "";
      form.value.goods_target_config_detail = [];
    } else {
      form.value.dimensionality = form.value.current_dimensionality;
    }
    form.value.dimensionality_type = form.value.dimensionality;
  }
};

// 新增
const createItemRef = ref();
const handleAdd = () => {
  if (!form.value.dimensionality) {
    return ElMessage.error("请选择目标维度");
  }
  // form.value.goods_target_config_detail.push({});
  createItemRef.value.open(form.value.dimensionality_type);
};

const hanldeCreateConfirm = (row) => {
  form.value.goods_target_config_detail.push(row);
};

// 删除
const handleDelete = (row, index) => {
  if (row.id) {
    row.delete = 1;
  } else {
    form.value.goods_target_config_detail.splice(index, 1);
  }
};

const rowClassName = ({ row }) => {
  if (row.delete === 1) {
    return "hidden-row";
  }
  return "";
};

// 批量操作
const hanldeBatch = (type) => {
  if (!form.value.goods_target_config_detail.length) {
    ElMessage.error("至少维护一条数据,才能进行批量操作");
    return;
  }
  batch_type.value = type;
  visibleBatch.value = true;
};

const batchSave = () => {
  if (batch_type.value == "value") {
    form.value.goods_target_config_detail.forEach((i) => {
      i.target_value = batchForm.value.target_value;
      return i;
    });
  } else if (batch_type.value == "manage") {
    form.value.goods_target_config_detail.forEach((i) => {
      i.target_manage = batchForm.value.target_manage;
      return i;
    });
  }
  batchClose();
};

// 关闭
const batchClose = () => {
  batch_type.value = "";
  batchForm.value = {};
  visibleBatch.value = false;
};

// 根据目标角色 过滤 目标类型
const designOptionsFilter = computed(() => {
  return designOptions.filter((i) => {
    if (form.value.target_rule == 1 || !form.value.target_rule) {
      if ([1, 2, 3].includes(i.value)) {
        return i;
      }
    } else {
      if ([4].includes(i.value)) {
        return i;
      }
    }
  });
});

const dimensionOptionsFilter = computed(() => {
  return dimensionOptions.filter((i) => {
    if (form.value.target_rule == 1 || !form.value.target_rule) {
      if ([1, 2].includes(i.value)) {
        return i;
      }
    } else {
      if ([1, 2, 3].includes(i.value)) {
        return i;
      }
    }
  });
});

const disabledDate = (time) => {
  const now = new Date();
  return time.getTime() < now.setHours(0, 0, 0, 0);
};

onMounted(() => {
  if (!commonStore.departmentOptions) {
    commonStore.getDepartmentList();
  }
  if (!commonStore.personnelOptions) {
    commonStore.getOrganization();
  }
  if (!commonStore.categoryOptions) {
    commonStore.getColumnsList();
  }
});

defineExpose({ open });

const changeUser = (val, row) => {
  row.target_manage = val;
};

const changePlatform = (val, row) => {
  row.platform_id_text = val;
};

const changeSite = (val, row) => {
  row.site_code = val.site_code;
};
</script>
<style lang="scss">
.label-color {
  .el-radio__input {
    display: none !important;
  }
}

.m-0 {
  margin: 0 !important;
}
</style>
